package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.commen.LabelVlalue;
import com.itheima.commen.R;
import com.itheima.commen.ReturnSuccess;
import com.itheima.dto.PageComDto;
import com.itheima.pojo.Subjects;
import com.itheima.service.SubjectsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 学科
 * @author 10049
 */


@RestController
@RequestMapping("/subjects")
public class SubjectsController {

    @Autowired
    private SubjectsService subjectsService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 修改学科
     */
    @PutMapping("/{id}")
    public ReturnSuccess updateById(@RequestBody Subjects subjects){
        subjectsService.updateById(subjects);
        return ReturnSuccess.success();
    }

    /**
     * 删除学科
     */
    @DeleteMapping("/{id}")
    public ReturnSuccess deleteById(@PathVariable Integer id){
        subjectsService.removeById(id);
        return ReturnSuccess.success();
    }

    /**
     * 添加学科
     */
    @PostMapping
    public Integer add(@RequestBody Subjects subjects){
        subjects.setAddDate(new Date());
        //todo 待完善,从seeion中获取userId
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        String jsonString = JSON.toJSONString(userId);
        Integer uid = JSON.parseObject(jsonString, Integer.class);
        subjects.setCreatorID(uid);
        subjects.setTags(0);
        subjects.setTotals(0);
        subjects.setTwoLevelDirectory(0);
        subjectsService.save(subjects);
        return subjects.getId();
    }
    /**
     * 学科简单列表
     */
    @GetMapping("/simple")
    public List<LabelVlalue> findAll(){
        LambdaQueryWrapper<Subjects> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Subjects::getId,Subjects::getSubjectName);
        List<Subjects> subjects = subjectsService.list(wrapper);
        ArrayList<LabelVlalue> labelVlalues = new ArrayList<>();
        for (Subjects subject : subjects) {
            LabelVlalue labelVlalue = new LabelVlalue();
            labelVlalue.setValue(subject.getId());
            labelVlalue.setLabel(subject.getSubjectName());
            labelVlalues.add(labelVlalue);
        }
        return labelVlalues;
    }
    /**
     * 学科详情
     */
    @GetMapping("/{id}")
    public Subjects findById(@PathVariable Integer id){
        Subjects subjects = subjectsService.getById(id);
        return subjects;
    }

    /**
     * 学科列表
     */
    @GetMapping
    public PageComDto findPage(Integer page, Integer pagesize, String subjectName){
        return subjectsService.findPage(page,pagesize,subjectName);
    }
}
